const websocket = require('ws')

const ws = websocket.Server({ port: 8080 })

let clients = {}
let clientNum = 0

ws.on('connection', (client) => {
    //监听，连接客户端

    //给每个连接的客户端创建一个名字
    clientNum.name = ++clientNum
    clients[client.name] = client //创建键值对 “1”：client实例

    //用client实例监听四个常用事件 open,message,error,close

    //监听客户端open事件，拿到客户端发来的信息
    client.on("message",()=>{
        console.log("用户"+client.name+"说:"+msg)
        broadcast(client,msg)
    })

    //监听客户端error事件，拿到客户端发来的错误
    client.on("error",()=>{
        if(err){
            console.log(err)
        }
    })

    //监听客户端close事件也就是下线事件
    client.on("close",()=>{
        broadcastQuite(client)
        console.log("用户"+client.name+"下线了!!!")
        delete clients[client.name] //从容器中删除下线的客户端实例
    })
})

 //广播方法
 function broadcast(client,msg){
     for(let key in clients){
         clients[key].send("用户"+client.name+"说:"+msg)
     }
 }

 //广播自己下线了
 function broadcasQuitet(client){
     for(let key in clients){
         clients[key].send("系统提示:用户"+client.name+"下线了!")
     }
 }